package com.qcu.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class PasswordUtils {

    // 生成随机盐
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 使用盐和密码生成哈希值
    public static String hashPassword(String password, String salt) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            digest.update(Base64.getDecoder().decode(salt));
            byte[] hash = digest.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 验证密码
    public static boolean verifyPassword(String password, String salt, String storedHash) {
        String hashToVerify = hashPassword(password, salt);
        return hashToVerify.equals(storedHash);
    }

    public static void main(String[] args) {
        String password = "123";

        // 生成盐
        String salt = generateSalt();
        System.out.println("Salt: " + salt);

        // 使用盐和密码生成哈希值
        String hashedPassword = hashPassword(password, salt);
        System.out.println("Hashed Password: " + hashedPassword);

        // 验证密码
        boolean isPasswordCorrect = verifyPassword(password, "JQU5d2LLvzcnGsqJK1dovg==", "ub86XqRNO4hT+l43gZ218m4tFdMcr0WoMcoND/je9cQ=");
        System.out.println("Password is correct: " + isPasswordCorrect);
    }
}
